package com.wjk.kylin.mall.gateway.exception;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.fastjson.JSON;
import com.wjk.kylin.mall.common.core.dto.base.BaseOutDTO;
import com.wjk.kylin.mall.common.core.exception.BaseError;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义限流降级返回json。方式二
 */
@Slf4j
@Component
public class SentinelGatewayBlockRequestHandler implements BlockRequestHandler {
    @Override
    public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable ex) {
        ServerHttpResponse serverHttpResponse = serverWebExchange.getResponse();
        serverHttpResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        serverHttpResponse.setStatusCode(HttpStatus.TOO_MANY_REQUESTS);

        BaseOutDTO dto = BaseOutDTO.error(BaseError.REQ_FLOW_ERR);

        if(ex instanceof DegradeException){
            serverHttpResponse.setStatusCode(HttpStatus.SERVICE_UNAVAILABLE);
            dto = BaseOutDTO.error(BaseError.REQ_DEGRADE_ERR);
        }
        String result = JSON.toJSONString(dto);

        log.error("API gateway error return json :{}",result);

        return ServerResponse.ok().body(Mono.just(result), String.class);
    }
}
